﻿using System.Collections.Generic;
using System.Linq;
using DataAccess.Entities;
using NHibernate;
using NHibernate.Criterion;

namespace DataAccess.Repositories
{
    public class RelationshipStatusRepository : IRepository<RelationshipStatus>
    {
        #region IRepository<RelationshipStatus> Members

        void IRepository<RelationshipStatus>.Save(RelationshipStatus entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<RelationshipStatus>.Update(RelationshipStatus entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(entity);
                    transaction.Commit();
                }
            }
        }

        void IRepository<RelationshipStatus>.Delete(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(id);
                    transaction.Commit();
                }
            }
        }

        RelationshipStatus IRepository<RelationshipStatus>.GetById(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<RelationshipStatus>().Add(Restrictions.Eq("Id", id)).UniqueResult<RelationshipStatus>();
        }

        IList<RelationshipStatus> IRepository<RelationshipStatus>.GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                IList<RelationshipStatus> temp = session.CreateCriteria<RelationshipStatus>().List<RelationshipStatus>();
                return session.CreateCriteria<RelationshipStatus>().List<RelationshipStatus>();
            }
        }

        public IList<RelationshipStatus> Find(string searchText, int maxResults)
        {
            IList<RelationshipStatus> interests;
            using (ISession session = NHibernateHelper.OpenSession())
                interests = session.CreateCriteria<RelationshipStatus>().List<RelationshipStatus>();

            var result = from n in interests
                         where n.Status.Contains(searchText)
                         orderby n.Status
                         select n;

            return result.Take(maxResults).ToList();
        }

        #endregion
    }
}
